package flashcardtest;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;
import flashcardtest.FlashCardSet;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;


public class NewDictionaryServlet extends HttpServlet implements Servlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// make sure we can get special characters
		if (request.getCharacterEncoding() == null)
			request.setCharacterEncoding("UTF-8");

		// read data from form
		String setName = request.getParameter("newname");
		String key1 = request.getParameter("key1");
		String key2 = request.getParameter("key2");

		// reset message
		request.getSession().setAttribute("message", "");
					
		// catch empty fields
		if (setName.equals("") || key1.equals("") || key2.equals("")) {
			request.getSession().setAttribute("message", "All fields must be filled in.");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/newdictionary.jsp");
			dispatcher.forward(request,response);
			return;
		}

		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		// determine if dictionary name is already used
		Query q = new Query("Dictionary");
		q.addFilter("name", Query.FilterOperator.EQUAL, setName);
		PreparedQuery pq = datastore.prepare(q);
		
		if (pq.countEntities(FetchOptions.Builder.withLimit(500)) > 0 ) {
			// there is already a dictionary with this name
			request.getSession().setAttribute("message", "There is already a dictionary named " + setName);
			response.sendRedirect("/newdictionary.jsp");

//			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/newdictionary.jsp");
	//		dispatcher.forward(request,response);
			return;
		}
		
		// Create Dictionary
		FlashCardSet flashcardset = new FlashCardSet(setName, key1, key2);
		request.getSession().setAttribute("flashcardset", flashcardset);

		Entity item = new Entity("Dictionary");
		item.setProperty("name", setName);
		item.setProperty("key1", key1);
		item.setProperty("key2", key2);
		datastore.put(item);
		
				
		// possible exceptions: DatastoreTimeoutException, ConcurrentModificationException, or DatastoreFailureException
		
	
		// redirect to edit dictionary page
		response.sendRedirect("/edit.jsp");

//		getServletContext().getRequestDispatcher("/edit.jsp").forward(request, response);

	
	}

}
